package com.qywx.service.impl;

import com.qywx.dao.SysUserDao;
import com.qywx.entity.SysUserEntity;
import com.qywx.service.SysLoginService;
import com.qywx.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @ClassName SysLoginServiceImpl
 * @Description: TODO
 * @Author wmj
 * @Date 2020/3/11
 * @Version V1.0
 **/
@Service("sysLoginService")
public class SysLoginServiceImpl implements SysLoginService {

    @Autowired
    SysUserDao sysUserDao;
    @Override
    public R login(String username, String password, HttpServletRequest request) throws NoSuchAlgorithmException {
        String encrypByMd5 = encrypByMd5(password);
        SysUserEntity sysUserEntity = sysUserDao.login(username,encrypByMd5);
        if(sysUserEntity!=null){
            int enable = sysUserEntity.getEnable();
            if(0==enable){
                return R.error("用户已禁用");
            }
            R r = new R();
            r.put("data",sysUserEntity);
            String token = UUID.randomUUID().toString();
            r.put("token", token);
            ServletContext servletContext = request.getServletContext();
            List originalToken = (List)servletContext.getAttribute("tokens");
            if(null!=originalToken&&originalToken.size()>0){
                //存在增加
                boolean add = originalToken.add(token);
                servletContext.setAttribute("tokens", originalToken);
            }else {
                //不存在直接放里面
                ArrayList<String> tokenList = new ArrayList<>();
                tokenList.add(token);
                servletContext.setAttribute("tokens",tokenList);
            }
            //servletContext.setAttribute("tokens", Arrays.asList(token));
            List tokens = (List) servletContext.getAttribute("tokens");
            System.out.println(tokens);
            return r;
        }else {
            return R.error("用户名或密码错误");
        }
    }

    @Override
    public R getSysUseEntity(Integer userid) {
        SysUserEntity sysUserEntity = sysUserDao.selectById(userid);
        R r = new R();
        r.put("data",sysUserEntity);
        return r;
    }

    @Override
    public R saveSysUser(SysUserEntity sysUserEntity) throws NoSuchAlgorithmException {
        String password = sysUserEntity.getPassword();
        String username = sysUserEntity.getUsername();
        String role = sysUserEntity.getRole();
        sysUserEntity.setCreatTime(new Date());
        if(password==null){
            return R.error("密码不能为空");
        }
        if(username==null){
            return R.error("用户名称不能为空");
        }
        if(role==null){
            return R.error("请选择用户角色");
        }
        SysUserEntity sysUser = sysUserDao.selectByName(username);
        if(sysUser!=null){
            return R.error("用户名已存在");
        }
        String encrypByMd5 = encrypByMd5(password);
        sysUserEntity.setPassword(encrypByMd5);
        sysUserEntity.setEnable(1);
        sysUserDao.insert(sysUserEntity);
        return R.ok();
    }

    @Override
    public R enableUser(Integer userid) {
        sysUserDao.enableUser(userid);
        return R.ok();
    }

    @Override
    public R forbiddenSysUser(String userid) {
        sysUserDao.forbiddenSysUser(userid);
        return R.ok();
    }

    @Override
    public R updateSysUser(String userid, String password) {
        String encrypByMd5 = encrypByMd5(password);
        sysUserDao.updateSysUser(userid,encrypByMd5);
        return R.ok();
    }

    @Override
    public R findSysUser(int page, int size) {
        if (page < 1) {
            page = 1;
        }
        if (size < 1) {
            size = 10;
        }
        int start = (page - 1) * size;
        List<SysUserEntity> sysUserEntityList = sysUserDao.find(start,size);
        int total = sysUserDao.getTotal();
        R r = new R();
        r.put("total", total);
        r.put("data", sysUserEntityList);
        return r;
    }

    //md5加密
    public String encrypByMd5(String password){
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        md.update(password.getBytes());
        byte [] encryContext = md.digest();//调用该方法完成计算
        int i;
        StringBuffer buf = new StringBuffer("");
        for (int offset = 0; offset < encryContext.length; offset++) {//做相应的转化（十六进制）
            i = encryContext[offset];
            if (i < 0) i += 256;
            if (i < 16) buf.append("0");
            buf.append(Integer.toHexString(i));
        }
        return buf.toString();
    }
}
